import { _decorator, Component, Collider2D, Contact2DType, IPhysics2DContact, RigidBody2D, PhysicsSystem2D, Vec3, Node, UITransform, ICollisionEvent, Animation, Prefab, instantiate, v2, color, Sprite, Color } from 'cc';
import { GameManager } from './GameManager';
import { ArrowController } from './ArrowController';
import { Joystick } from './Joystick';


const { ccclass, property } = _decorator;

@ccclass('BirdController')
export class BirdController extends Component {
    @property
    moveSpeed: number = 300;

    @property(Node)
    gameManager: Node = null;

    // 空节点
    @property(Joystick)
    joystick: Joystick = null;

    // 小鸟是否被击中活着
    isAlive: boolean = true;

    // 是否短暂冲刺
    private isDashing = false;

    ani:Animation;

    //子弹速度
    @property
    public bulletSpeed:number =100;

    //小鸟是否开火
     private isBulleting = false;

     @property(Node)
     bulletContainer:Node = null;


    // 是否处于无敌状态
    private _isInvincible: boolean = false;

    
    public invincibleDuration: number = 1; 

    // 小鸟发射子弹
    @property(Prefab)
    bulletPrefab: Prefab;

    start() {
         this.ani = this.getComponent(Animation);
        // 获取当前节点上的 Collider2D
         const collider = this.getComponent(Collider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this); // 2D 写法

        } else {
            // console.warn('未找到 Collider2D 组件');
        }

    
    }
  

    update(dt: number) {
        //小鸟被弓箭射中后就不能再动了
        if (!this.isAlive) return; 

        const dir = this.joystick.getDirection();
        if (dir.length() > 0) {
            const move = new Vec3(dir.x, dir.y, 0).multiplyScalar(this.moveSpeed * dt);
            const nextPos = this.node.position.add(move);

            // 边界限制
            const halfWidth = 720 / 2;
            const halfHeight = 1280 / 2;

            const nodeSize = this.node.getComponent(UITransform).contentSize;
            const halfNodeWidth = nodeSize.width / 2;
            const halfNodeHeight = nodeSize.height / 2;

            // 限制X轴范围
            nextPos.x = Math.max(-halfWidth + halfNodeWidth, Math.min(halfWidth - halfNodeWidth, nextPos.x));
            // 限制Y轴范围
            nextPos.y = Math.max(-halfHeight + halfNodeHeight, Math.min(halfHeight - halfNodeHeight, nextPos.y));

            this.node.setPosition(nextPos);
        }
    }


    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // console.log(otherCollider.name)
        // const arrow = otherCollider.getComponent(ArrowController);
        const gameManagerCtrl = this.gameManager.getComponent(GameManager);
        if (otherCollider.name.includes('Arrow')) {
            // console.log('小鸟被弓箭射中！');
            this.onHitByArrow();
           
            
            gameManagerCtrl.onGameOver(); 
        }else if(otherCollider.name.includes('Food')){

            this.ani.play('fishSmile');
            this.scheduleOnce(() => {
                this.ani.play('fish');
                this.isBulleting = false;
            }, 1);
            
            // 延迟销毁食物节点
            this.scheduleOnce(() => {
                otherCollider.node.destroy(); // 不再立即 destroy，避免物理引擎崩溃
            }, 0.1);

            //吃到食物加5分
            gameManagerCtrl.addScore(5);
            gameManagerCtrl.spawnFood();
        }
    }

    //direction.multiplyScalar(this.moveSpeed) 将方向向量（direction）乘上一个速度标量 moveSpeed，得到「本次要移动的距离向量」
    move(direction: Vec3) {
        this.node.setPosition(this.node.position.add(direction.multiplyScalar(this.moveSpeed)));
    }

    dash() {
        // console.log('冲刺前速度'+this.moveSpeed)
        if (this.isDashing) return;
        this.isDashing = true;
        this.moveSpeed=400;
        // console.log(this.ani.name)
        this.ani.play('dash');
        this.scheduleOnce(() => {
            this.moveSpeed = 200;
            this.ani.play('fish');
            this.isDashing = false;
        }, 0.3); // 冲刺持续 0.2 秒变为原来速度
    }


    onHitByArrow() {
        this.isAlive = false;
        // console.log('小鸟死亡，不再移动');
        // 可选：播放死亡动画或特效
    }

 

    // 一秒发射一个子弹,子弹5秒后销毁
    fireBullet() {
        if(this.isBulleting) return;
        const bullet = instantiate(this.bulletPrefab);
        this.bulletContainer.addChild(bullet);
        bullet.setWorldPosition(this.node.getWorldPosition()); // 从小鸟发射

        // // 子弹5秒后销毁
        // this.scheduleOnce(() => {
        //     // 子弹自身销毁
        //     bullet.destroy();
        // }, 10);

        this.isBulleting =true;
        this.ani.play('dash');
        this.scheduleOnce(() => {
            this.ani.play('fish');
            this.isBulleting = false;
        }, 0.5);  

        
       
    }



       /**
     * 开始无敌状态（禁用碰撞）
     */
    public startInvincible() {
        const collider = this.getComponent(Collider2D);
        if (!collider) return;

        this._isInvincible = true;
        collider.enabled = false;

        // 无敌可视化提示（可选）
        const sprite = this.node.getComponent(Sprite);
        if (sprite) {
            sprite.color = Color.fromHEX(new Color(), '#f24b4bff'); // 红色
        }

        // 定时恢复碰撞
        this.scheduleOnce(() => {
            this.endInvincible();
        },this.invincibleDuration);
    }


       /**
     * 结束无敌状态
     */
    private endInvincible() {
         const collider = this.getComponent(Collider2D);
        if (!collider) return;

        this._isInvincible = false;
        collider.enabled = true;

        // 恢复颜色
         const sprite = this.node.getComponent(Sprite);
        if (sprite) {
            sprite.color = Color.fromHEX(new Color(), '#edededff'); 
        }
        // console.log("[碰撞系统] 无敌状态结束");
    }

}




